package com.wosiliujing.learning.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wosiliujing.learning.admin.dto.MenuTree;
import com.wosiliujing.learning.admin.dto.ResourcesTree;
import com.wosiliujing.learning.admin.po.SysResources;
import com.wosiliujing.learning.admin.po.SysRoleResources;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.constant.enums.ResourcesTypeEnum;
import com.wosiliujing.learning.mapper.SysResourcesMapper;
import com.wosiliujing.learning.service.SysResourcesService;
import com.wosiliujing.learning.service.SysRoleResourcesService;
import com.wosiliujing.learning.util.TreeUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: liujing
 * @date: 2019/5/6 22:07
 * @description:
 */
@AllArgsConstructor
@Service
public class SysResourcesServiceImpl extends ServiceImpl<SysResourcesMapper, SysResources> implements SysResourcesService {

    private final SysRoleResourcesService sysRoleResourcesService;

    @Override
    public List<MenuTree> menuTrees(List<String> permissions) {
        List<MenuTree> menuTrees =  this.list(Wrappers.<SysResources>lambdaQuery().in(SysResources::getPermission,permissions))
                .stream()
                    .filter(sysResources -> StrUtil.equals(sysResources.getType(),ResourcesTypeEnum.MENU_LEFT.getValue()))
                    .map(sysResources -> {
                        MenuTree menuTree = new MenuTree();
                        BeanUtils.copyProperties(sysResources,menuTree);
                        return menuTree;
                    }).collect(Collectors.toList());
        return TreeUtil.buildTree(menuTrees,CommonConstants.TREE_ROOT);
    }

    @Override
    public List<ResourcesTree> resourcesTrees() {
        List<ResourcesTree> resourcesTrees = this.list(Wrappers.emptyWrapper())
                .stream()
                    .map(sysResources -> {
                        ResourcesTree resourcesTree = new ResourcesTree();
                        BeanUtils.copyProperties(sysResources,resourcesTree);
                        return resourcesTree;
                    }).collect(Collectors.toList());
        return TreeUtil.buildTree(resourcesTrees, CommonConstants.TREE_ROOT);
    }

    @Override
    public List<String> getCurrentUserResourcesIds(String roleId) {
        return sysRoleResourcesService.list(Wrappers.<SysRoleResources>lambdaQuery().eq(SysRoleResources::getRoleId,roleId))
                .stream()
                    .map(SysRoleResources::getResourcesId)
                    .collect(Collectors.toList());
    }
}
